import { applyMiddleware, combineReducers, createStore } from 'redux'
import { composeWithDevTools } from 'redux-devtools-extension'
import thunk, { ThunkMiddleware } from 'redux-thunk'
import { readonly, ref } from 'vue'
import app from './modules/app'
import user from './modules/user'
import { State, StateReducer, StoreAction } from './types/store'

const stateReducer: StateReducer = {
  app,
  user
}

const store = (() => {
  /* 使用插件时
  return createStore(counterReducer, composeWithDevTools({})(
    applyMiddleware(...插件列表)
  ))
  */
  if (import.meta.env.DEV) {
    const composeEnhancers = composeWithDevTools({ name: 'Hello-Vue3' })
    return createStore(
      combineReducers(stateReducer),
      composeEnhancers(applyMiddleware(thunk as ThunkMiddleware<State, StoreAction>))
    )
  }
  return createStore(combineReducers(stateReducer), applyMiddleware(thunk as ThunkMiddleware<State, StoreAction>))
})()

const createdRefs = <T extends object>(getModulesState: () => T) => {
  const refs = ref<T>(getModulesState())
  store.subscribe(() => {
    if (getModulesState() !== refs.value) {
      refs.value = getModulesState()
    }
  })
  return () => readonly(refs)
}

const appStore = {
  ...store,
  useUserRef: createdRefs(() => store.getState().user),
  useAppRef: createdRefs(() => store.getState().app)
}

export default appStore
